package io.renren.modules.sys.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.QuestionEntity;
import io.renren.modules.sys.service.QuestionService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 题目列表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-10-31 17:53:34
 */
@RestController
@RequestMapping("sys/question")
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Value("${web.upload-path}")
    private  String path;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:question:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = questionService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:question:info")
    public R info(@PathVariable("id") Integer id){
        QuestionEntity question = questionService.getById(id);

        return R.ok().put("question", question);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:question:save")
    public R save(@RequestBody QuestionEntity question){
        questionService.save(question);

        return R.ok();
    }

    /**
     * 信息
     */
    @RequestMapping("/infoName/{questionsId}")
    public R infoName(@PathVariable("questionsId") String questionsId){
        String url = "";
        if (StringUtils.isNotBlank(questionsId)&&questionsId.length()>0&&!questionsId.equals("null")){

            String[] strarr = questionsId.split(",");
            if(strarr.length>0){
                for(String idstr:strarr){
                    if ("null".equals(idstr)||StringUtils.isBlank(idstr)){
                        continue;
                    }
                    int id = Integer.parseInt(idstr);
                    QuestionEntity questionEntity = questionService.getById(id);
                    url+=questionEntity.getNameimg()+",";
                }
            }
//            String questionid = "";
//            for (int i=0;i<questionsId.length();i++) {
//                questionid=questionsId.substring(i, i+1);
//                if (",".equals(questionid)) {
//                    continue;
//                }
//                QuestionEntity questionEntity = questionService.getById(Integer.parseInt(questionid));
//                url=url+questionEntity.getNameimg()+",";
//            }
        }
        url = url.substring(0, url.lastIndexOf(','));
        return R.ok().put("data", url);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:question:update")
    public R update(@RequestBody QuestionEntity question){
        ValidatorUtils.validateEntity(question);
        questionService.updateById(question);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:question:delete")
    public R delete(@RequestBody Integer[] ids){
        questionService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

//    private final String  urlLogo="http://127.0.0.1:8081/renren-admin/upload/";
    private final String  urlLogo="https://znb.cunlab.com/img/";
    @RequestMapping(value="/upload",method= RequestMethod.POST)
    @ResponseBody
    public R uploadLogo(MultipartFile file, HttpServletRequest request)throws Exception{
        SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
//        String storePath= path;//存放我们上传的文件路径
        String urlPath=urlLogo;
        if (!file.isEmpty()) {
            String fileName =new Date().getTime()+".jpg";
            String storePath="/www/server/images";
//            String storePath=request.getSession().getServletContext().getRealPath("")+"/img";
            File filepath = new File(storePath);
            if (!filepath.exists()) {
                filepath.mkdirs();//如果目录不存在，创建目录
            }
            try {
                file.transferTo(new File(storePath+"/"+fileName));//把文件写入目标文件地址
            } catch (Exception e) {
                e.printStackTrace();
                return R.error();
            }
            Map<String, String> content=new HashMap<>();
            content.put("first","您好,图片已经更新");
            content.put("keyword1","图片更新");
            content.put("keyword3", sdf.format(new Date()));
            return R.ok().put("fileName",urlPath+fileName).put("url",urlPath+fileName);
        }else {
            return R.error();
        }
    }
}
